package com.autoplaza;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Denunciar extends Activity implements Runnable{
	String[] opciones={"Error en las fotos","Ya está vendido","Precio incorrecto","Teléfono incorrecto",
			"Descripción incorrecta","Anuncio repetido","Otro problema","Dirección incorrecta"};
	String idanuncio, result;
	ProgressDialog pd;
	int opcion=99;
	
	
	Handler handler=new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(getApplicationContext(), "Mensaje enviado correctamente", Toast.LENGTH_SHORT).show();
			pd.dismiss();
			pd.cancel();
			
		};
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.denunciar);
		
		int size = Utils.getScreenSize2(Denunciar.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			idanuncio = extras.getString("numanuncio");
			
			
			ListView list=(ListView) findViewById(R.id.listadenuncia);
			
			 ItemsAdapter ItemsAdapter = new ItemsAdapter(
					    Denunciar.this, R.layout.itemsimple,
					    opciones);
			
			
			list.setAdapter(ItemsAdapter);
			
			list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					if(isNetwork()==true){
						progreso();	
						opcion=arg2;
					}else{
						dialogoInternet();
					}
					
				}
			});
		}

	
	}
	
	
	void progreso(){
		pd=ProgressDialog.show(this, "Espere por favor...", "Buscando...");
		Thread thread=new Thread(this);
		thread.start();
		
	}
	
	@Override
	public void run() {
		enviarDenuncia();
		
	}
	
	 private void enviarDenuncia() {
		  InputStream is = null;
			
			try{
			String url="http://www.autoplaza.com.mx/systems/Admin/Problemas/xt_ControlCalidadNETblack.asp?" +
					"AnuID="+idanuncio+"&SisID=35&Calidad="+opcion;
			
			Log.i("URL", ""+url);

			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
			
			if (httpEntity != null) {
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString();

				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
			
			}catch (Exception e) {
			}
			
			handler.sendEmptyMessage(0);		
	}
	 
	 
	 public boolean isNetwork(){
	    	boolean bool = false;
	    	HttpGet requestForTest = new HttpGet("http://m.google.com");
	        try {
	            new DefaultHttpClient().execute(requestForTest); // can last...
	            bool = true;
	        } catch (Exception e) {}
			return bool;
	    }
	    
		private void dialogoInternet() {
			AlertDialog.Builder builder = new AlertDialog.Builder(Denunciar.this);
			builder.setMessage("Necesita conexión a Internet")
			       .setCancelable(false)
			       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			           }
			       });
			AlertDialog alertDialog = builder.create();
			alertDialog.show();		
									
		}
		
	 

	private class ItemsAdapter extends BaseAdapter {
		  String[] items;

		  public ItemsAdapter(Context context, int textViewResourceId,
		    String[] items) {
		   // super(context, textViewResourceId, items);
		   this.items = items;
		  }

		  // @Override
		  public View getView(int position, View convertView, ViewGroup parent) {
		   
		   View v = convertView;
		   if (v == null) {
		    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    v = vi.inflate(R.layout.itemsimple, null);
		   } 
		   TextView post = (TextView) v
		     .findViewById(R.id.post);
		   post.setText(items[position]);
		   
		   return v;
		  }

		  public int getCount() {
		   return items.length;
		  }

		  public Object getItem(int position) {
		   return position;
		  }

		  public long getItemId(int position) {
		   return position;
		  }
		 }



	
	
}
